<?php

namespace Managers;

class Pages extends BaseManager {

    protected $__table = '\Catalog\Pages';

    public function qb() {
        $qb = $this->_em->getRepository($this->__table)->createQueryBuilder('c');
        return $qb;
    }

    public function getById($id) {

        $res = $this->_em->createQueryBuilder()
                ->select('page', 'type')
                ->from($this->__table, 'page')
                ->join('page.type', 'type')
                ->where('page.id = :id')->setParameter('id', $id)
                ->setMaxResults(1)
                ->getQuery()
                ->getArrayResult();
      
        return count($res) ? $res[0] : false;
    }

    public function getByTypeLocale($type, $locale) {

        $res = $this->_em->createQueryBuilder()
                ->select('page')
                ->from($this->__table, 'page')
                ->where('page.type = :type')->setParameter('type', $type)
                ->andWhere('page.locale = :locale')->setParameter('locale', $locale)
                ->getQuery()
                ->getArrayResult();

        return count($res) ? $res[0] : false;
    }

    public function getMenu($locale, $parent = null) {
        $qb = $this->_em->createQueryBuilder()
                ->select('partial r.{id, title, color, sort}')
                ->from($this->__table, 'r');
        if ($parent) {
            $qb = $qb->where('r.parent = :parent')
                    ->setParameter('parent', $parent);
        } else {
            $qb = $qb->where('r.parent is null');
        }

        $res = $qb->andWhere('r.locale = :locale')->setParameter('locale', $locale)
                ->orderBy('r.sort', 'ASC')
                ->getQuery()
                ->getArrayResult();

        foreach ($res as $i => $record) {
            $res[$i]['children'] = $this->getMenu($locale,$record['id']);
        }

        return $res;
    }

}
